package com.dlc.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.bean.model.StockChangeReason;
import com.dlc.shop.bean.model.StockChangeReasonLang;
import com.dlc.shop.bean.model.StockChangeReasonStatus;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.enums.StatusEnum;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.i18n.LanguageEnum;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.dao.StockChangeReasonMapper;
import com.dlc.shop.dao.StockChangeReasonStatusMapper;
import com.dlc.shop.manager.impl.LangManager;
import com.dlc.shop.service.StockChangeReasonLangService;
import com.dlc.shop.service.StockChangeReasonService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 *
 *
 * @author LGH
 * @date 2021-09-07 16:04:18
 */
@Service
@AllArgsConstructor
public class StockChangeReasonServiceImpl extends ServiceImpl<StockChangeReasonMapper, StockChangeReason> implements StockChangeReasonService {

    private final StockChangeReasonMapper stockChangeReasonMapper;
    private final StockChangeReasonStatusMapper stockChangeReasonStatusMapper;
    private final StockChangeReasonLangService stockChangeReasonLangService;
    private final LangManager langManager;

    @Override
    public IPage<StockChangeReason> pageByParams(PageParam<StockChangeReason> page, StockChangeReason stockChangeReason) {
        IPage<StockChangeReason> stockChangeReasonPage = stockChangeReasonMapper.pageByParams(page, stockChangeReason);
        langManager.getStockChangeReasonLang(stockChangeReasonPage.getRecords());
        return stockChangeReasonPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void  saveInfo(StockChangeReason stockChangeReason) {
        // 校验信息
        this.checkInfo(stockChangeReason, true);
        // 设置默认值
        stockChangeReason.setStatus(StatusEnum.ENABLE.value());
        // 保存出入库原因
        stockChangeReasonMapper.insert(stockChangeReason);
        this.saveLangList(stockChangeReason.getStockChangeReasonId(), stockChangeReason.getStockChangeReasonLangList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateInfo(StockChangeReason stockChangeReason) {
        stockChangeReasonLangService.remove(Wrappers.lambdaQuery(StockChangeReasonLang.class)
                .eq(StockChangeReasonLang::getStockChangeReasonId, stockChangeReason.getStockChangeReasonId())
        );
        // 校验信息
        this.checkInfo(stockChangeReason, false);
        stockChangeReasonMapper.updateById(stockChangeReason);
        this.saveLangList(stockChangeReason.getStockChangeReasonId(), stockChangeReason.getStockChangeReasonLangList());
    }

    private void saveLangList(Long stockChangeReasonId, List<StockChangeReasonLang> stockChangeReasonLangList) {
        checkStockChangeReasonLang(stockChangeReasonLangList);
        stockChangeReasonLangList.forEach(item -> {
            item.setStockChangeReasonId(stockChangeReasonId);
        });
        stockChangeReasonLangService.saveBatch(stockChangeReasonLangList);
    }

    private void checkStockChangeReasonLang(List<StockChangeReasonLang> stockChangeReasonLangList) {
        Integer lang = langManager.getDefaultLang();
        boolean containsMaster = false;
        for (StockChangeReasonLang stockChangeReasonLang : stockChangeReasonLangList) {
            if (Objects.equals(stockChangeReasonLang.getLang(), lang)) {
                containsMaster = true;
            }
        }
        if (!containsMaster) {
            throw new YamiShopBindException("语言数据已更新，请重新录入商品信息");
        }
    }

    @Override
    public List<StockChangeReason> listByParams(StockChangeReason stockChangeReason) {
        List<StockChangeReason> stockChangeReasons = stockChangeReasonMapper.listByParams(stockChangeReason);
        langManager.getStockChangeReasonLang(stockChangeReasons);
        return stockChangeReasons;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeStatus(Long shopId, Long stockChangeReasonId, Integer status) {
        StockChangeReason stockChangeReason = stockChangeReasonMapper.selectById(stockChangeReasonId);
        if (Objects.equals(stockChangeReason.getShopId(), Constant.PLATFORM_SHOP_ID) && !Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
            // 商家端改变系统内置的出入库原因状态
            if (Objects.equals(status, StatusEnum.DELETE.value())) {
                //系统内置出入库原因不能删除
                throw new YamiShopBindException("yami.system.reason.not.delete");
            }
            StockChangeReasonStatus stockChangeReasonStatus = stockChangeReasonStatusMapper.selectOne(Wrappers.lambdaQuery(StockChangeReasonStatus.class)
                    .eq(StockChangeReasonStatus::getShopId, shopId)
                    .eq(StockChangeReasonStatus::getStockChangeReasonId, stockChangeReasonId)
            );
            if (Objects.isNull(stockChangeReasonStatus)) {
                stockChangeReasonStatus = new StockChangeReasonStatus();
                stockChangeReasonStatus.setStockChangeReasonId(stockChangeReasonId);
                stockChangeReasonStatus.setShopId(shopId);
                stockChangeReasonStatus.setStatus(status);
                stockChangeReasonStatusMapper.insert(stockChangeReasonStatus);
            } else {
                stockChangeReasonStatus.setStatus(status);
                stockChangeReasonStatusMapper.updateById(stockChangeReasonStatus);
            }
        } else {
            this.update(Wrappers.lambdaUpdate(StockChangeReason.class)
                    .set(StockChangeReason::getStatus, status)
                    .eq(StockChangeReason::getStockChangeReasonId, stockChangeReasonId)
                    .eq(StockChangeReason::getShopId, shopId)
            );
        }
    }

    @Override
    public StockChangeReason getInfoByIdAndShopId(Long stockChangeReasonId, Long shopId) {
        StockChangeReason stockChangeReason = stockChangeReasonMapper.getInfoByIdAndShopId(stockChangeReasonId, shopId);
        langManager.getStockChangeReasonAndLang(stockChangeReason);
        return stockChangeReason;
    }

    /**
     * 校验信息
     * @param stockChangeReason 出入库原因
     * @param saveOrUpdate true: 保存时校验  false: 更新时校验
     */
    private void checkInfo(StockChangeReason stockChangeReason, Boolean saveOrUpdate) {
        if (!saveOrUpdate && Objects.isNull(stockChangeReason)) {
            throw new YamiShopBindException("id不能为空");
        }
        for (StockChangeReasonLang stockChangeReasonLang : stockChangeReason.getStockChangeReasonLangList()) {
            int count = stockChangeReasonLangService.countReason(stockChangeReason, stockChangeReasonLang.getReason());
            if (count > 0) {
                throw new YamiShopBindException(Objects.equals(stockChangeReasonLang.getLang(), LanguageEnum.LANGUAGE_ZH_CN.getLang())
                        ? "yami.cn.reason.duplicate" : "yami.en.reason.duplicate");
            }
        }
    }
}
